import { iup } from '../../util';
import type { PrintParams } from './interface';
import { openPrintModal } from './PrintModal';
import { getPrintTemplate } from './service';
import { info, wfAlert } from './util';

const MAX_PRINT_COUNT = 2147483647;
/**
 * 打印
 * @param params
 * @private
 */
async function _printWithPdKey(params: any) {
  const { batchPrintList, bizCode } = params;
  if (batchPrintList.length === 0) {
    await wfAlert(info.alertTitle, info.selectOneData);
  } else {
    const res = await getPrintTemplate({
      pageSize: MAX_PRINT_COUNT,
      pageIndex: 1,
      bizCode: bizCode,
      isFilterProject: true,
      isEnable: true
    });
    const templateData: any = res?.list || [];
    await openPrintModal({
      ...params,
      data: templateData
    });
  }
}

/**
 * 打印接口
 * @param bizType
 * @param bizPhid
 * @param callback
 * @param cancelback
 */
async function _print(batchPrintList, bizCode, source_sys, callback, cancelback) {
  await _printWithPdKey({ batchPrintList, bizCode, source_sys, cancelback, callback });
}

/**
 * 打印api
 */
const $Print = {
  // 打印
  print(params: PrintParams) {
    return new Promise((resolve, reject) => {
      const batchPrintList = params?.batchPrintList || params?.bacthPrintList || params?.id;
      _print(
        batchPrintList,
        params.bizCode,
        params.source_sys,
        (...args) => {
          params.successCallback?.(...args);
          resolve(args);
        },
        (...args) => {
          params.cancelCallback?.(...args);
          reject(args);
        }
      ).then();
    });
  }
};

iup.registerExternal({
  getPrintSdk() {
    return $Print;
  }
});

export { $Print };
export type Print = typeof $Print;
